package com.lcx.plugin.tool;

import com.intellij.credentialStore.CredentialAttributes;
import com.intellij.credentialStore.CredentialAttributesKt;
import com.intellij.credentialStore.Credentials;
import com.intellij.ide.passwordSafe.PasswordSafe;

/**
 * @author daxiong
 * @date 2023/6/20 下午2:24
 */
public class PassUtil {

    public static CredentialAttributes createCredentialAttributes(String key) {
        return new CredentialAttributes(
                CredentialAttributesKt.generateServiceName("EasyDb", key));
    }

    /**
     * 根据key获取密码
     *
     * @param key
     * @param username
     * @return java.lang.String
     * @author daxiong
     * @date 2023/6/20 下午2:27
     */
    public static String getPass(String key, String username) {
        // e.g. serverURL, accountID
        CredentialAttributes credentialAttributes = createCredentialAttributes(formatKey(key, username));

        Credentials credentials = PasswordSafe.getInstance().get(credentialAttributes);
        if (credentials != null) {
            return credentials.getPasswordAsString();
        }
        return null;
    }

    /**
     * 保存用户名和密码
     *
     * @param key
     * @param username
     * @param password
     * @return void
     * @author daxiong
     * @date 2023/6/20 下午2:29
     */
    public static void savePass(String key, String username, String password) {
        CredentialAttributes credentialAttributes = createCredentialAttributes(formatKey(key, username));
        Credentials credentials = new Credentials(username, password);
        PasswordSafe.getInstance().set(credentialAttributes, credentials);
    }

    public static String formatKey(String key, String username) {
        return key + "@" + username;
    }

}
